package com.example.practicespring.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;

public class PwdUtils {

    private static final Pattern SPECIAL_CHAR_PATTERN = Pattern.compile("[.!@#$%^&*()_+{}\":<>?]");
    private static final Logger log = LoggerFactory.getLogger(PwdUtils.class);

    public static String getSHA256Hash(String input) {
        try {
            // 创建MessageDigest的实例，初始化为SHA-256算法
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            // 使用指定的字节数组更新摘要
            md.update(input.getBytes());

            // 完成哈希计算，得到结果
            byte[] digest = md.digest();

            // 将哈希值转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }

            // 返回哈希值的十六进制字符串
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static Boolean checkPassword(String password) {
        if (password == null || password.length() < 8) {
            return false;
        }

        // 检查大写字母
        boolean hasUpperCase = Pattern.matches(".*[A-Z].*", password);
        log.info("hasUpperCase: {}", hasUpperCase);
        // 检查小写字母
        boolean hasLowerCase = Pattern.matches(".*[a-z].*", password);
        log.info("hasLowerCase: {}", hasLowerCase);
        // 检查数字
        boolean hasDigit = Pattern.matches(".*\\d.*", password);
        log.info("hasDigit: {}", hasDigit);
        // 检查特殊字符
        boolean hasSpecialChar = SPECIAL_CHAR_PATTERN.matcher(password).find();
        log.info("hasSpecialChar: {}", hasSpecialChar);
        return hasUpperCase && hasLowerCase && hasDigit && hasSpecialChar;
    }

}
